package com.cskaoyan.user.controller;

import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.MyUserLoginResponse;
import com.cskaoyan.user.dto.TestUserLoginDto;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.dto.UserLoginResponseGet;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Aaliyah
 * @date 2022/9/21 17:49
 * @description: TODO
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    ILoginService loginService;

    @PostMapping("/login")
    public ResponseData postUserLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request, HttpServletResponse response){
        MyUserLoginResponse userLoginResponse = loginService.postUserLogin(userLoginRequest,request,response);
        String token = userLoginResponse.getToken();
        Cookie access_token = new Cookie("access_token", token);
        access_token.setPath("/");
        response.addCookie(access_token);
        if (UserRetCode.SUCCESS.getCode().equals(userLoginResponse.getCode())){
            return new ResponseUtil<MyUserLoginResponse>().setData(userLoginResponse);
        }
        return new ResponseUtil<MyUserLoginResponse>().setErrorMsg(userLoginResponse.getMsg());
    }

    // @GetMapping("/login")
    // public ResponseData getUserLogin(){
    //     // loginService.getUserLogin().
    //     TestUserLoginDto testUserLoginDto = new TestUserLoginDto(73, null);
    //     ResponseUtil<TestUserLoginDto> responseUtil = new ResponseUtil<>();
    //
    //     return responseUtil.setData(testUserLoginDto);
    // }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ResponseData getUserLogin (HttpServletRequest request){
        UserLoginResponseGet userLoginResponseGet = loginService.getUserLogin(request);
        return new ResponseUtil().setData(userLoginResponseGet);
    }


    @RequestMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response) {
        // loginService.loginOut();

        Cookie access_token = new Cookie("access_token", null);
        access_token.setPath("/");
        access_token.setMaxAge(0);
        response.addCookie(access_token);

        return new ResponseUtil().setData(null);
    }
}
